package com.whut.monitor.netty.handler;

import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.apache.log4j.Logger;

import java.net.SocketTimeoutException;

/**
 * @author qing
 * 心跳包机制
 */
public class KeepAliveHeartFilter extends ChannelDuplexHandler {
    private static final Logger logger = Logger.getLogger(KeepAliveHeartFilter.class);
    private static final String HEART_REQUEST = "HEART_REQUEST_MESSAGE";
    private static final String HEART_RESPONSE = "HEART_RESPONSE_MESSAGE";

    //接收到心跳消息不传给后面的Handler
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg.toString().trim().equals(HEART_REQUEST)){
            logger.info("接收到" + ctx.channel().remoteAddress() + "心跳包");
            ctx.writeAndFlush(HEART_RESPONSE);
            return;
        }
        super.channelRead(ctx, msg);
    }

    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
        if (msg.equals(HEART_RESPONSE)){
            logger.info("发送" + ctx.channel().remoteAddress() + "心跳包");
            return;
        }else {
            logger.info("发送" + ctx.channel().remoteAddress() + "消息" + msg.toString());
        }
        super.write(ctx, msg, promise);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        super.userEventTriggered(ctx, evt);
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state() == IdleState.READER_IDLE) {
                ctx.channel().close();
                throw new SocketTimeoutException();
            }
        }
    }
}
